var zTree;
var setting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyunionget/getPartyUnionDeptTree",// Ajax 获取数据的 URL 地址
        autoParam: ["deptId"],// 异步加载时需要自动提交父节点属性的参数
    },
    callback: {
        onClick: zTreeOnClick
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "orgLevelId",
            rootPId: "0"
        },
        key: {
            name: "deptName"
        }
    }
};
var setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/partyunionget/getPartyUnionDeptTree",// Ajax 获取数据的 URL 地址
        autoParam: ["deptId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        // 禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "orgLevelId",
            rootPId: "0"
        },
        key: {
            name: "deptName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree
                .getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.deptId;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].deptName + ",";
                vid += nodes[i].deptId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            var nameem = $("#deptId");
            nameem.val(v);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            nameem.attr("data-value", vid);
            nameem.val(v);
        }
    }
};
$(function () {
    $('#remark').summernote({height: 200});
    var topNode1 = [{
        deptName: orgName,
        orgLevelId: '',
        isParent: "true",
        deptId: "0",
        icon: "/gobal/img/org/org.png"
    }];
    var topNode = [{deptName: orgName, orgLevelId: '', isParent: "true", deptId: "0", icon: "/gobal/img/org/org.png"}];
    zTree = $.fn.zTree.init($("#tree"), setting, topNode);// 初始化树节点时，添加同步获取的数据
    var nodes = zTree.getNodes();
    var zTreeObj = $.fn.zTree.init($("#menuTree"), setting1, topNode1);
    var nodes1 = zTreeObj.getNodes();
    for (var i = 0; i < nodes.length; i++) {
        zTree.expandNode(nodes[i], true, false, false);// 默认展开第一级节点
    }
    for (var i = 0; i < nodes1.length; i++) {
        zTreeObj.expandNode(nodes1[i], true, false, false);// 默认展开第一级节点
    }
    query("")
    $(".js-query").unbind("click").click(function () {
        $("#infodiv").hide();
        $("#list").show();
    })
    $(".js-addbtn").unbind("click").click(function () {
        document.getElementById("form").reset();
        $("#accountId").attr("data-value");
        $("#deptId").attr("data-value");
        $("#list").hide();
        $("#infodiv").show();
        $("#updatabut").hide();
        $("#createbut").show();
    })
    getPartyUnionLevelList();
    jeDate("#joinTime", {
        format: "YYYY-MM-DD"
    });
    jeDate("#birthday", {
        format: "YYYY-MM-DD"
    });

    $("#deptId").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });

    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });

    $("#createbut").unbind("click").click(function () {
        addInsertPartyUnionMember()
    })
});

function zTreeOnClick(event, treeId, treeNode) {
    $("#infodiv").hide();
    $("#list").show();
    $("#myTable").bootstrapTable('destroy');
    if (treeNode.deptId == "0") {
        query("");
    } else {
        query(treeNode.deptId);
    }
}

function query(deptId) {
    $("#myTable").bootstrapTable({
        url: '/ret/partyunionget/getPartyUnionMemberListByDeptId?deptId=' + deptId,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'memberId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: '序号',//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'cardId',
                width: '150px',
                title: '身份证号码'
            },
            {
                field: 'userName',
                title: '人员姓名',
                width: '80px'
            },
            {
                field: 'userSex',
                title: '性别',
                width: '50px'
            },
            {
                field: 'deptName',
                width: '100px',
                title: '基层名称'
            },
            {
                field: 'tel',
                width: '100px',
                title: '联系电话'
            },
            {
                field: 'joinTime',
                width: '100px',
                title: '入会时间'
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                width: '150px',
                formatter: function (value, row, index) {
                    return createOptBtn(row.memberId);
                }
            }],
        onClickCell: function (field, value, row, $element) {
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}


function createOptBtn(memberId) {
    var html = "<a href=\"javascript:void(0);edit('" + memberId + "')\" class=\"btn btn-darkorange btn-xs\" >编辑</a>";
    html += "&nbsp;&nbsp;<a href=\"javascript:void(0);deleterecord('" + memberId + "')\" class=\"btn btn-primary btn-xs\">删除</a>";
    html += "&nbsp;&nbsp;<a href=\"javascript:void(0);details('" + memberId + "')\" class=\"btn btn-sky btn-xs\">详情</a>";
    return html;
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order
    };
    return temp;
};

function details(memberId) {
    window.open("/app/core/partyunion/setmemberdetails?memberId=" + memberId);
}

function edit(memberId) {
    document.getElementById("form").reset();
    $("#accountId").attr("data-value");
    $("#deptId").attr("data-value");
    $("#file_img").attr("src", "/assets/img/avatars/adam-jansen.jpg");
    $("#list").hide();
    $("#infodiv").show();
    $("#createbut").hide();
    $("#updatabut").show();
    $.ajax({
        url: "/ret/partyunionget/getPartyUnionMemberById",
        type: "post",
        dataType: "json",
        data: {
            memberId: memberId
        },
        success: function (data) {
            if (data.status == 200) {
                let info = data.list;
                for (let id in info) {
                    if (id == "accountId") {
                        $("#" + id).attr("data-value", info[id]);
                        var userName = getUserNameByStr(info[id]);
                        $("#" + id).val(userName);
                        $("#userName").val(userName);
                    } else if (id == "userName") {

                    } else if (id == "userSex") {
                        $("input[name='userSex'][value='" + info[id] + "']").attr("checked", true);
                    } else if (id == "photos") {
                        $("#file_img").attr("src", "/sys/file/getStaticImg?module=govphotos&fileName=" + info[id]);
                        $("#file").attr("data-value", info[id])
                    } else if (id == "remark") {
                        $("#remark").code(info[id]);
                    } else if (id == "deptId") {
                        $("#" + id).attr("data-value", info[id]);
                        $.ajax({
                            url: "/ret/partyunionget/getPartyUnionDeptById",
                            type: "post",
                            dataType: "json",
                            data: info[id],
                            success: function (data) {
                                if (data.status == "500") {
                                    console.log(data.msg);
                                } else if (data.status == "100") {
                                    layer.msg(sysmsg[data.msg]);
                                } else {
                                    $("#deptId").val(data.list.deptName);
                                }
                            }
                        })
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $("#updatabut").unbind("click").click(function () {
                    updatePartyUnionMember(memberId);
                })
            } else if (data.status == 100) {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }
        }
    });
}

function deleterecord(userId) {
    if (confirm("确定删除当前工会成员信息吗？")) {
        $.ajax({
            url: "/set/partyunionset/deletePartyUnionMember",
            type: "post",
            dataType: "json",
            data: {
                userId: userId
            },
            success: function (data) {
                if (data.status == 200) {
                    layer.msg(sysmsg[data.msg]);
                    location.reload();
                } else if (data.status == 100) {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    } else {
        return;
    }
}

function getPartyUnionLevelList() {
    $.ajax({
        url: "/ret/partyunionget/getPartyUnionLevelForList",
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                let infoList = data.list;
                $("#levelId").append("<option value=''>请选择</option>");
                for (let i = 0; i < infoList.length; i++) {
                    $("#levelId").append("<option value='" + infoList[i].levelId + "'>" + infoList[i].levelName + "</option>");
                }
            }
        }
    })
}

function delPhotos() {
    $("#file_img").attr("src", "/assets/img/avatars/adam-jansen.jpg");
    $("#file").attr("data-value", "");
}

function addInsertPartyUnionMember() {
    $.ajax({
        url: "/set/partyunionset/insertPartyUnionMember",
        type: "post",
        dataType: "json",
        data: {
            sortNo: $("#sortNo").val(),
            accountId: $("#accountId").attr("data-value"),
            userName: $("#userName").val(),
            photos: $("#file").attr("data-value"),
            userSex: getCheckBoxValue("userSex"),
            cardId: $("#cardId").val(),
            birthday: $("#birthday").val(),
            levelId: $("#levelId").val(),
            deptId: $("#deptId").attr("data-value"),
            joinTime: $("#joinTime").val(),
            tel: $("#tel").val(),
            remark: $("#remark").code()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#infodiv").hide();
                $("#list").show();
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}

function updatePartyUnionMember(memberId) {
    $.ajax({
        url: "/set/partyunionset/updatePartyUnionMember",
        type: "post",
        dataType: "json",
        data: {
            memberId: memberId,
            sortNo: $("#sortNo").val(),
            accountId: $("#accountId").attr("data-value"),
            userName: $("#userName").val(),
            photos: $("#file").attr("data-value"),
            userSex: getCheckBoxValue("userSex"),
            cardId: $("#cardId").val(),
            birthday: $("#birthday").val(),
            levelId: $("#levelId").val(),
            deptId: $("#deptId").attr("data-value"),
            joinTime: $("#joinTime").val(),
            tel: $("#tel").val(),
            remark: $("#remark").code()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#infodiv").hide();
                $("#list").show();
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}
